package com.atguigu.gmall.web.all.config;

import com.atguigu.gmall.common.cache.GmallCacheAspect;
import com.atguigu.gmall.common.handler.GlobalExceptionHandler;
import com.atguigu.gmall.feign.AppFeignConfig;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lsj
 * @create 2021-08-21 1:32
 */
//@EnableFeignClients({
//        "com.atguigu.gmall.feign.item",
//        "com.atguigu.gmall.feign.product",
//        "com.atguigu.gmall.feign.search",
//        "com.atguigu.gmall.feign.cart",
//        "com.atguigu.gmall.feign.user",
//        "com.atguigu.gmall.feign.order"
//})
@EnableFeignClients({"com.atguigu.gmall.feign"})
@EnableAspectJAutoProxy
@Configuration
@Import({GmallCacheAspect.class, AppFeignConfig.class, GlobalExceptionHandler.class})
public class ServiceWebConfig {

    //配置自己的业务线程池 核心业务线程池
    @Bean("corePool")
    public ThreadPoolExecutor executor(ThreadConfigProperties properties) {
        return new ThreadPoolExecutor(
                properties.core,
                properties.max,
                properties.keepalive, //线程池 1min了都没有活要干了
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(properties.queueLength),
                new MyItemServiceThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    // 从properties中获取参数
    @Component
    @ConfigurationProperties(prefix = "order-service.thread")
    @Data
    class ThreadConfigProperties {
        private Integer core;
        private Integer max;
        private Long keepalive;
        private Integer queueLength;
    }

    // 自定义线程工厂
    class MyItemServiceThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("order-service: "+ UUID.randomUUID().toString().substring(0,5));
            return thread;
        }
    }

}
